/*
 * Copyright 2014 Facebook, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#pragma once
#include <memory>
#include <folly/wangle/Future.h>

namespace folly { namespace wangle {

/**
  The ThreadGate strategy encapsulates a bidirectional gate via two Executors,
  kind of like a stargate for wangle Future chains. Its implementation is
  slightly more efficient then using Future::via in both directions, and if
  the pattern is common it can be more convenient (although the overhead of
  setting up a ThreadGate is less convenient in most situations).

    // Using a ThreadGate (which has two executors xe and xw)
    tg.gate(a).then(b);

    // Using via
    makeFuture()
      .via(xe).then(a)
      .via(xw).then(b);

  If you're not sure whether you want a ThreadGate, you don't. Use via.

  There are two actors, the east thread which does the asynchronous operation
  (the server) and the west thread that wants the asynchronous operation done
  (the client).

  The client calls gate<T>(fn), which returns a Future<T>. Practically speaking
  the returned Future<T> is the same as the Future<T> returned by fn. But
  there are actually two futures involved - the original Future which will be
  generated by fn (called the east Future), and the Future actually returned
  by gate<T>(fn) (called the west Future).

  These two futures are decoupled, and although the fulfilment of the east
  Future eventually causes fulfilment of the west Future, those fulfilments
  happen in their own threads.

  In order to make and use a ThreadGate, you need to provide a strategy for
  executing code in the east and west threads. These strategies may be
  different. The only requirement is a threadsafe method
  `void add(function<void()>&&)`.

  In order for your ThreadGate to do anything, you need to drive those
  executors somehow. An event loop is a natural fit. A thread pool might be
  made to work. You could use a busy loop to make a very expensive space
  heater. 0MQ would be pleasant.

  Another pattern supported by the ThreadGate is the single-thread pattern. In
  this pattern, non-blocking I/O drives the asynchronous operation, and
  futures are fulfilled in an event loop callback. In this scenario,
  ThreadGate is largely superfluous, and the executors would likely just
  execute code immediately and inline (and therefore not need to be driven, or
  threadsafe). But a Waiter strategy that makes progress by driving the event
  loop one iteration would allow for gate-and-wait code which is agnostic to
  the small detail that everything happens in one thread. It would also make
  Future change toward a multithreaded architecture easier, as you need only
  change the components of the ThreadGate which your client code is already
  using.
  */
class ThreadGate {
public:
  virtual ~ThreadGate() {}

  /**
    Returns a Future that will be fulfilled after the Future that will be
    returned by fn() has been fulfilled, with the same value or exception
    (moved).

    There's a lot of nuance in that sentence. Let's break it down.

    fn kicks off the asynchronous operation (makes the east Promise), and must
    be executed in the east thread because the east thread is where the east
    Promise will be fulfilled. Since gate is being called from the west
    thread, we must gate fn using the east executor. fn is not executed
    immediately, it is queued up and will be executed by the east thread as it
    drives the executor.

    We create the west Promise and return its Future.

    When the east thread executes its task, fn is called and the resulting
    Future gets a callback that will gate another task back to the west.

    Sometime later, the asynchronous operation completes and the east Promise
    is fulfilled. Then the east Future executes its callback, which adds a
    task to the west executor that task is to fulfil the west Promise with the
    same Try<T>, and it will execute in the west thread.

    At this point, the west Future is still unfulfilled, even though the east
    Future has been fulfilled and its callback has finished executing. Only
    when the west executor is driven to execute that task, the west Future
    will be completed and its callbacks called.

    In summary, both east and west need to have plans to drive their
    executors, or nothing will actually happen. When the executors are driven,
    then everything flows. */
  template <class T>
  Future<T> gate(std::function<Future<T>()>&& fn) {
    Promise<T> pWest;
    Future<T> fWest = pWest.getFuture();

    gate(std::move(fn), std::move(pWest));
    return fWest;
  }

  /**
   * This version of gate is to support use cases where the calling thread is
   * not the west thread. Here is an example use case.
   *
   *  Promise<T> pWest;
   *  Future<T> fWest = pWest.getFuture();
   *
   *  // Set up callbacks for west from a thread that is not west.
   *  fWest.then(...).then(...);
   *
   *  threadGate.gate(..., std::move(pWest));
   *
   * This function assumes that it is safe to call addEast from a thread that is
   * not the west thread.
   */
  template <class T>
  void gate(std::function<Future<T>()>&& fn,
            Promise<T>&& p) {
    folly::MoveWrapper<Promise<T>> pWest(std::move(p));
    folly::MoveWrapper<std::function<Future<T>()>> fnm(std::move(fn));
    this->addEast([pWest, fnm, this]() mutable {
      (*fnm)().then([pWest, this](Try<T>&& t) mutable {
        folly::MoveWrapper<Try<T>> tm(std::move(t));
        this->addWest([pWest, tm]() mutable {
          pWest->fulfilTry(std::move(*tm));
        });
      });
    });
  }

  /**
    If your workflow calls for synchronizing with a
    west Future, then you may call waitFor, but if your west thread is
    event-driven you will probably not need to call waitFor.

    In order for waitFor to behave properly, you must ensure that the Waiter's
    makeProgress method causes some progress to be made on the west thread,
    i.e. drives the west executor either directly or indirectly.

    (Naturally, progress needs to be made on the east thread as well. i.e. the
    east executor is driven, the asynchronous operation happens, and its
    Promise is fulfilled. It is likely that none of this concerns the consumer
    of waitFor.)

    This is the only function that uses the Waiter. It is never called
    internally. Therefore, if you never use waitFor you can safely provide a
    DummyWaiter.
    */
  template <class T>
  void waitFor(Future<T> const& f) {
    while (!f.isReady()) {
      this->makeProgress();
    }
  }

  template <class T>
  typename std::add_lvalue_reference<T>::type
  value(Future<T>& f) {
    waitFor<T>(f);
    return f.value();
  }

  template <class T>
  typename std::add_lvalue_reference<const T>::type
  value(Future<T> const& f) {
    waitFor<T>(f);
    return f.value();
  }

  virtual void addEast(std::function<void()>&&) = 0;
  virtual void addWest(std::function<void()>&&) = 0;
  virtual void makeProgress();
};

}} // namespace
